package com.grm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grm.common.Result;
import com.grm.entity.QuartzTask;
import com.grm.service.QuartzService;
import com.grm.service.QuartzTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/quartz")
public class JobController {
    @Autowired
    private QuartzService quartzService;

    @Autowired
    private QuartzTaskService quartzTaskService;

    @PostMapping("/job")
    public Result addJob(@RequestBody QuartzTask quartzTask){
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name",quartzTask.getTaskName());
        QuartzTask queryResult = quartzTaskService.getOne(queryWrapper);
        if (queryResult != null){
            return Result.failed(500,"任务名称已存在!");
        }
        quartzTaskService.save(quartzTask);
        return Result.success("操作成功!");
    }

    @PutMapping("/job")
    public Result updateJob(@RequestBody QuartzTask quartzTask){
        //判断任务是否启用
        Boolean status = quartzTaskService.getById(quartzTask.getId()).getStatus();
        if (status){
            return Result.failed(500,"任务正在运行中，请暂停后修改!");
        }
        //判断任务名称是否重名
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name",quartzTask.getTaskName());
        QuartzTask queryResult = quartzTaskService.getOne(queryWrapper);
        if (queryResult != null &&!queryResult.getId().equals(quartzTask.getId())){
            return Result.failed(500,"任务名称已存在!");
        }
        quartzTaskService.updateById(quartzTask);
        return Result.success("操作成功!");
    }

    @DeleteMapping("/job/{id}")
    public Result deleteJob(@PathVariable Integer id){
        //判断任务是否启用
        Boolean status = quartzTaskService.getById(id).getStatus();
        if (status){
            return Result.failed(500,"任务正在运行中，请暂停后删除!");
        }
        quartzTaskService.removeById(id);
        return Result.success("操作成功!");
    }

    @GetMapping("/job")
    public Result getJobPage(Page<QuartzTask> page,QuartzTask params){
        QueryWrapper<QuartzTask> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(params.getDes())){
            queryWrapper.like("des",params.getDes());
        }
        if (StringUtils.isNotEmpty(params.getTaskName())){
            queryWrapper.like("task_name",params.getTaskName());
        }
        if (StringUtils.isNotEmpty(params.getGroupName())){
            queryWrapper.like("group_name",params.getGroupName());
        }
        if (params.getStatus() != null){
            queryWrapper.eq("status",params.getStatus());
        }
        queryWrapper.orderByDesc("id");
        IPage<QuartzTask> result = quartzTaskService.page(page,queryWrapper);
        return Result.success("操作成功",result);
    }
    /**
     * 修改任务的cron
     *
     * @return
     */
    @RequestMapping(value = "/updateJobCron",method = RequestMethod.PUT)
    public Result updateJobCron(Integer id, String cron) {
        QuartzTask quartzTask = quartzTaskService.getById(id);
        //如果存在quartzTask对象
        if (quartzTask != null) {
            //修改任务的cron
            quartzTask.setCron(cron);
            //更新quart_task
            quartzTaskService.updateById(quartzTask);
            //如果启用状态则修改当前已持久化的job
            if (quartzTask.getStatus()) {
                quartzService.updateJob(quartzTask);
            }
            return Result.success("修改cron成功");
        }
        //不存在quartzTask对象
        return Result.failed(500,"修改cron失败");
    }

    /**
     * 是否启用接口
     *
     * @return
     */
    @PutMapping(value = "/jobStatus")
    public Result updateJobStatus(@RequestBody QuartzTask params) {
        QuartzTask quartzTask = quartzTaskService.getById(params.getId());
        if (quartzTask != null) {
            //修改任务的启用状态
            quartzTask.setStatus(params.getStatus());
            //更新quart_task
            boolean updateResult = quartzTaskService.updateById(quartzTask);
            //根据status判断是新增job还是删除job
            if (params.getStatus() && updateResult) {
                quartzService.addJob(quartzTask);
            } else if (updateResult){
                quartzService.deleteJob(quartzTask);
            }
            return Result.success("修改状态成功");
        }
        return Result.failed(500,"修改状态失败");
    }

    /**
     * 启用一次任务
     * @author  **
     * @param id 任务id
     * @return java.lang.Object
     */
    @PostMapping("/runJob/{id}")
    public Result runJobOnce(@PathVariable Integer id){
        QuartzTask quartzTask = quartzTaskService.getById(id);
        if (quartzTask != null) {
            quartzService.runJobOnce(quartzTask);
            return Result.success("任务执行成功");
        }
        return Result.failed(500,"任务执行失败");
    }
}

